package com.sirui.x.io.netty;

import java.nio.charset.Charset;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

@Sharable
public class Utf8ServerHandle extends ChannelInboundHandlerAdapter {
	
	public Utf8ServerHandle() {
		logger.info("utf 8 server handle init...");
	}

	private static final Logger logger = LoggerFactory.getLogger(Utf8ServerHandle.class);

	public static final Charset UTF_8 = Charset.forName("UTF-8");

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		ByteBuf in = (ByteBuf) msg;
		logger.info("server recieve: {}", in.toString(UTF_8));
		ctx.write(in);
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) {
		ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); // 将未决消息[4]冲刷到远程节点，并且关闭该Channel
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		logger.error("", cause);
		ctx.close();
	}
}
